package models

import (
	"github.com/jinzhu/gorm"
	"kop/modules/treasure/configuration"
	"kop/modules/treasure/consts"
	"kop/modules/treasure/entity"
	"kop/pb"
	"time"
)

func AutoMigrate(dB *gorm.DB) {

	dB.AutoMigrate(new(entity.Treasure))
	dB.AutoMigrate(new(entity.TreasureGrade))
}

func GetTreasure(dB *gorm.DB, roleID int32) pb.Treasure {

	var t = entity.Treasure{
		RoleID:   roleID,
		MapID:    0,
		PlayNum:  3,
		CellsArr: []*pb.Cell{},
	}

	if err := dB.FirstOrCreate(&t).Error; err != nil {
		panic(err)
	}

	return buildPbTreasure(t)
}

func SaveTreasure(dB *gorm.DB, treasure *pb.Treasure) {

	var addPoint = treasure.AddPoint
	var t = entity.Treasure{
		RoleID:         treasure.RoleID,
		MapID:          treasure.MapID,
		PlayNum:        treasure.PlayNum,
		Number:         treasure.Number,
		Point1:         treasure.Point1,
		Point2:         treasure.Point2,
		Point3:         treasure.Point3,
		Point4:         treasure.Point4,
		Buff1:          treasure.Buff1,
		Buff2:          treasure.Buff2,
		Buff3:          treasure.Buff3,
		CellsArr:       treasure.Cells,
		BuffOptionsArr: treasure.BuffOptions,
	}

	if err := dB.Save(&t).Error; err != nil {
		panic(err)
	}

	*treasure = buildPbTreasure(t)
	treasure.AddPoint = addPoint
}

func buildPbTreasure(t entity.Treasure) pb.Treasure {

	var treasure = pb.Treasure{
		RoleID:      t.RoleID,
		PlayNum:     t.PlayNum,
		MapID:       t.MapID,
		Number:      t.Number,
		Point1:      t.Point1,
		Point2:      t.Point2,
		Point3:      t.Point3,
		Point4:      t.Point4,
		Buff1:       t.Buff1,
		Buff2:       t.Buff2,
		Buff3:       t.Buff3,
		Cells:       t.CellsArr,
		BuffOptions: t.BuffOptionsArr,
	}

	if t.MapID > 0 {
		var conf, err = configuration.GetTreasureByMapID(t.MapID)
		if err != nil {
			panic(err)
		}
		treasure.CostCoin = conf.CostCoin
	} else if t.PlayNum < consts.MaxPlayNum {

		var now = time.Now().Unix()

		for i := int32(0); i < consts.MaxPlayNum; i++ {
			var future = t.UpdatedAt.Unix() + int64(i)*int64(consts.Interval)
			if future > now {
				treasure.RefreshSec = int32(future - now)
			}
		}
	}

	return treasure
}
